package br.ufsm.inf.zebraloqacliente.activities;

import java.util.List;
import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import org.json.JSONException;
import org.json.JSONObject;

import br.ufsm.inf.zebraloqacliente.R;
import br.ufsm.inf.zebraloqacliente.dbhelper.JSONParser;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class LoginActivity extends Activity implements OnClickListener{

	private EditText user, pass;
	private Button mSubmit, mRegister;

	 // Progress Dialog
    private ProgressDialog pDialog;

    // JSON parser class
    JSONParser jsonParser = new JSONParser();

    //php login script location:

    //localhost :
    //testing on your device
    //put your local ip instead,  on windows, run CMD > ipconfig
    //or in mac's terminal type ifconfig and look for the ip under en0 or en1
    // private static final String LOGIN_URL = "http://xxx.xxx.x.x:1234/webservice/login.php";

    //testing on Emulator:
    //private static final String LOGIN_URL = "http://10.0.2.2:8000/api/v1/user/lfschleder/";
    private static final String LOGIN_URL = "http://10.0.2.2:8000/api/v1/user/";

    //testing from a real server:
    //private static final String LOGIN_URL = "http://www.yourdomain.com/webservice/login.php";

    //JSON element ids from response of php script:
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_MESSAGE = "message";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);

		//setup input fields
		user = (EditText)findViewById(R.id.login);
		pass = (EditText)findViewById(R.id.senha);

		//setup buttons
		mSubmit = (Button)findViewById(R.id.entrar);
		mRegister = (Button)findViewById(R.id.cadastrarse);

		//register listeners
		mSubmit.setOnClickListener(this);
		mRegister.setOnClickListener(this);

	}

	@Override
	public void onClick(View v) {
		// determine which button was pressed:
		switch (v.getId()) {
		case R.id.entrar:
				new AttemptLogin().execute();
			break;
		case R.id.cadastrarse:
				Intent i = new Intent(this, CadastrarActivity.class);
				startActivity(i);
			break;

		default:
			break;
		}
	}

	//AsyncTask is a separate thread than the thread that runs the GUI
	//Any type of networking should be done with async task.
	//three methods get called, first preExecture, then do in background, and once do		
	//in back ground is completed, the onPost execute method will be called.
	class AttemptLogin extends AsyncTask<String, String, String> {

		/**
        * Before starting background thread Show Progress Dialog
        * */
		boolean failure = false;

       @Override
       protected void onPreExecute() {
           super.onPreExecute();
           pDialog = new ProgressDialog(LoginActivity.this);
           pDialog.setMessage("Tentando fazer login...");
           pDialog.setIndeterminate(false);
           pDialog.setCancelable(true);
           pDialog.show();           
       }

		@Override
		protected String doInBackground(String... args) {            			
		   // Check for success tag
           int success;
           String username = user.getText().toString();
           String password = pass.getText().toString();
           try {
               // Building Parameters
               List<NameValuePair> params = new ArrayList<NameValuePair>();
               params.add(new BasicNameValuePair("username", username));
               params.add(new BasicNameValuePair("password", password));

               Log.d("request!", "starting");
               // getting product details by making HTTP request
               
               JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "GET", params);
               // LF mudei esta linha
               //JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST", params);

               // check your log for json response               
               Log.d("Login attempt", json.toString());

               // json success tag
               Log.d("LF DEBUG", "vai tentar o json.getInt");
               success = json.getInt(TAG_SUCCESS);
               Log.d("LF DEBUG", "fez o json.getInt");
               
               
               if (success == 1) {               
	               	Log.d("Tá logado!", json.toString());
	               	// quando se loga, vai para a tela de busca:
	               	Intent i = new Intent(LoginActivity.this, BuscaActivity.class);
	               	finish();
	   				startActivity(i);
	               	return json.getString(TAG_MESSAGE);
               } else {
	               	Log.d("Não logou!", json.getString(TAG_MESSAGE));
	               	return json.getString(TAG_MESSAGE);
               }
           } catch (JSONException e) {
               e.printStackTrace();
           }

           return null;

		}
		
		/**
        * After completing background task Dismiss the progress dialog
        * **/
        protected void onPostExecute(String file_url) {
           // dismiss the dialog once product deleted
           pDialog.dismiss();
           if (file_url != null){
           	Toast.makeText(LoginActivity.this, file_url, Toast.LENGTH_LONG).show();
           }

       }

	}

}